import uviewPlus from "uview-plus";
import formatMoney from "@/utils/formatMoney";


import {createSSRApp} from 'vue'
import App from './App.vue'
//全局空状态
import empty from "@/components/empty"
//vuex
import store from '@/store/index.js';
// 引入全局方法
// import globalMethods from '@/static/js/globalMethods.js';
import CryptoJS from 'crypto-js'
import getLoction from "@/utils/getLoction";
// 仅在App端有效
let hasPermission = false;

async function checkAndRequestStoragePermission(permission='android.permission.CAMERA') {

    // 主动申请权限
    return new Promise((resolve) => {
        //#ifdef H5
        resolve (true);
        //#endif
        console.log('>主动申请权限>',hasPermission)

        if (hasPermission) {
            resolve (true);
        }
        // const permission = "android.permission.WRITE_EXTERNAL_STORAGE";
        if (plus.android.checkPermission(permission)) {
            // 已有权限
            resolve (true);

        }
        console.log('>主动申请权限>')
        plus.android.requestPermissions([permission], (result) => {
            resolve(result.granted.length > 0);
            hasPermission = true;
            resolve(true)
        }, () => {
            resolve(false);
        });
    });
}
export function createApp() {
    const app = createSSRApp(App)
    app.component('empty', empty)
    // 全局取消打印
    if (process.env.NODE_ENV == 'production') {
        console.log = () => {
        };
    }
    app.use(uviewPlus);

    console.log("版本:", process.env.NODE_ENV)
    // 项目配置
    app.config.globalProperties.$store = wx
    app.config.globalProperties.$store = store
    app.config.globalProperties.$template = store.state.template
    app.config.globalProperties.$defaultAvatar = store.state.defaultAvatar
    app.config.globalProperties.$baseurl = store.state.baseurl
    app.config.globalProperties.$share = store.state.share
    app.config.globalProperties.$SHOPbaseurl = store.state.SHOPbaseurl
    app.config.globalProperties.$CryptoJS = CryptoJS
    app.config.globalProperties.$formatMoney = formatMoney;

    // #ifdef H5
    // 设置favicon
    const favicon = document.createElement('link')
    favicon.rel = 'shortcut icon'
    favicon.href = store.state.logo // 替换为你的图标地址
    document.head.appendChild(favicon)
    // #endif

		app.config.globalProperties.$setPhone = (phone) => { //隐私手机号
			return phone.substr(0, 3) + '****' + phone.substr(7)
		}
    app.config.globalProperties.$md5Encrypt = (text) => {
        let h = app.config.globalProperties.$CryptoJS.MD5(text).toString(CryptoJS.enc.Hex).slice(0,
            16).toUpperCase();
        return app.config.globalProperties.$stringToBase64(h).substring(0, 16);
    };
    // 字符串转换为Base64
    app.config.globalProperties.$stringToBase64 = (str) => {
        // 将字符串转换为ArrayBuffer
        var buffer = new ArrayBuffer(str.length);
        var view = new Uint8Array(buffer);
        for (var i = 0; i < str.length; i++) {
            view[i] = str.charCodeAt(i);
        }
        return uni.arrayBufferToBase64(buffer);
    }
    // 判断是否在微信浏览器   true是
    app.config.globalProperties.$isWeiXinBrowser = () => {
        // #ifdef H5
        // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
        let ua = window.navigator.userAgent.toLowerCase()
        // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true
        } else {
            return false
        }
        // #endif
        return false
    }
    app.config.globalProperties.$decrypt = (encryptWord) => {
        try {
            return app.config.globalProperties.$CryptoJS.enc.Utf8.stringify(app.config
                .globalProperties.$CryptoJS.AES
                .decrypt(encryptWord, app.config.globalProperties.$CryptoJS.enc.Utf8.parse(app
                    .config.globalProperties
                    .$md5Encrypt(app.config.globalProperties.$store.state.key)), {
                    mode: app.config.globalProperties.$CryptoJS.mode.ECB,
                    padding: app.config.globalProperties.$CryptoJS.pad.Pkcs7,
                })).toString();
        } catch (e) {
            return JSON.stringify(encryptWord)
            //TODO handle the exception
        }
    }
    // 判断是否在微信浏览器true是
    app.config.globalProperties.$isWeiXinBrowser = function () {
        // #ifdef H5
        // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
        let ua = window.navigator.userAgent.toLowerCase()
        // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true
        } else {
            return false
        }
        // #endif
        return false
    }
    // 注册$showPrompt到Vue原型上，以方便全局调用
    app.config.globalProperties.$showPrompt = function (option) {
        if (typeof option === 'object') {
            // #ifndef H5
            // if (option.hideTabBar) {
            // 	wx.hideTabBar();
            // }
            // #endif
            app.config.globalProperties.$store.commit('showPrompt', option)
        } else {
            throw "配置项必须为对象传入的值为：" + typeof option;
        }
    }
    // 定义全局方法
    app.config.globalProperties.$goURl = (url) => { //全局跳转封装
        if (url.indexOf('/pages/') != -1) {
            if ( url.indexOf('/pages/index/index') != -1 ||
                url.indexOf('/pages/vicinity/vicinity') != -1 || url.indexOf(
                    '/pages/personal/index') != -1 || url.indexOf('/pages/commodity/category') != -1
            ) {
                uni.navigateTo({
                    url: url
                })
            } else {
                uni.navigateTo({
                    url: url
                })
            }
        } else if (url.indexOf('http://') != -1 || url.indexOf('https://') != -1) {
            if (url.indexOf('https://work.weixin.qq.com') != -1) {
                // #ifdef H5
                window.location.href = url
                // #endif
                // #ifdef APP-PLUS
                plus.runtime.openURL(url);
                // #endif
            } else {
                uni.setStorageSync('appletid', 0)
                uni.setStorageSync('applet', url)
                uni.navigateTo({
                    url: '/pages/applet/applet'
                })
            }

        } else {
            if (url.goodsType == 0) {
                uni.navigateTo({
                    url: url.link
                })
            } else if (url.goodsType == 1) {
                uni.navigateTo({
                    url: `/pages/commodity/details?id=${url.link}`
                })
            } else if (url.goodsType == 2) {
                uni.navigateTo({
                    url: `/pages/commodity/category?id=${url.link}`
                })
            }
            // #ifndef MP-WEIXIN
            // uni.showToast({
            // 	icon: 'none',
            // 	title: '暂未开放,敬请期待'
            // })
            // #endif

        }
    }
    // 定义装修跳转全局方法
    app.config.globalProperties.$gotosUrls = (obj) => { //全局跳转封装
        if (obj.link == '') {
            // #ifndef  MP-WEIXIN
            uni.showToast({
                icon: 'none',
                title: '暂未开放'
            })
            return false;
            //  #endif
        }
        var Tab = Tab = ['pages/index/index', '/pages/cat/cat', '/pages/personal/index',
            '/pages/commodity/category', '/pages/vicinity/vicinity'
        ]
        if (Tab.indexOf(obj.link) != -1) {
            uni.switchTab({
                url: obj.link
            })
            return
        }
            //暂时对外部链接不考虑
            //  else if (obj.link.indexOf("www") >= 0 || obj.link.indexOf("http") >= 0 || obj.link.indexOf("https") >= 0) {
            // 	uni.navigateTo({
            // 		url: `/pages/company/skip?url=${url}`
            // 	})
        // }
        else {
            if (obj.goodsType == 0) {
                uni.navigateTo({
                    url: obj.link
                })
            } else if (obj.goodsType == 1) {
                uni.navigateTo({
                    url: `/pages/commodity/details?id=${obj.link}`
                })
            } else if (obj.goodsType == 2) {
                uni.navigateTo({
                    url: `/pages/commodity/partition?type=1&id=${obj.link}`
                })
            }
        }
    }
    app.config.globalProperties.$payList = (str) => {
        let is_h5
        // #ifdef APP-PLUS
        is_h5 = 0
        // #endif
        // #ifdef H5
        if (app.config.globalProperties.$isWeiXinBrowser()) {
            is_h5 = 3
        } else {
            is_h5 = 1
        }
        // #endif
        // #ifdef MP-WEIXIN
        is_h5 = 2
        // #endif
        app.config.globalProperties.$request({
            url: `api/payType/?is_h5=${is_h5}`,
            method: 'GET',
            success(res) {
                if (res.errno == 0) {
                    console.log("res", res)
                    let list = res.data.sort((a, b) => {
                        return Number(b.sort) - Number(a.sort)
                    })
                    uni.setStorageSync('payType', list)
                }
            }
        })
    }
    app.config.globalProperties.$evalPro = (str) => { //已废弃
        var Fn = Function;
        return new Fn('return ' + str)();
    }
    app.config.globalProperties.$toFiexd = (num, index) => { //保留小数
        if (num === undefined || num === null) {
            return '0.00'
        }
        if (typeof num === 'string') {
            num = parseFloat(num)
        }

        return Number(num).toFixed(index)
    }
    app.config.globalProperties.$clearTime = (time) => { //处理时间
        return time.replace('T', ' ').split('.')[0]
    }
    app.config.globalProperties.$toast = (str) => {
        uni.showToast({
            icon: "none",
            title: str
        })
    }
    app.config.globalProperties.$isIos = () => { //判断是否ios
        let platform = uni.getSystemInfoSync().platform;
        return platform === 'ios'
    }
    app.config.globalProperties.$isAuto = () => { //是否登录
        let token = ''
        try {
            token = uni.getStorageSync('userInfo').token
        } catch (e) {

        }
        if (token) {
            return true
        } else {
            return false
        }
    }
    app.config.globalProperties.$sellPrice = (row) => { //处理进货价和卖价
        // let str = (((parseFloat(row.price) - parseFloat(row.amount)) / 2) + parseFloat(row.amount)).toFixed(2)
        let price = parseFloat(row.price)
        let amount = parseFloat(row.amount)
        let str = 0
        if (amount * 1.1 > price) {
            str = (price - amount) / 100 * 20 + amount
        } else {
            str = amount * 1.1
        }
        return str.toFixed(2)
    }

    app.config.globalProperties.$userInfo = (data) => { //全局接口请求
        let token = ''
        try {
            token = uni.getStorageSync('userInfo').token
        } catch (e) {

        }
        uni.request({
            url: app.config.globalProperties.$baseurl + 'api/user_info/',
            method: 'GET',
            header: {
                'token': token,
                'encryption': app.config.globalProperties.$store.state.encryption
            },
            success: res => {
                if (app.config.globalProperties.$store.state.encryption) {
                    try {
                        res.data.data = JSON.parse(app.config.globalProperties.$decrypt(
                            res.data.data))
                    } catch (e) {
                        //TODO handle the exception
                    }

                }
                if (res.statusCode == 200) {

                    uni.setStorageSync('userInfo', res.data.data);
                    // app.config.globalProperties.$store.state.name=res.data.data.project_name
                    data&&  data.success&& data.success(res.data);
                } else if (res.statusCode == 403) {
                    uni.setStorageSync('userInfo', {});
                    // #ifdef MP-WEIXIN
                    uni.switchTab({
                        url: '/pages/personal/index'
                    });
                    // #endif
                    // #ifndef MP-WEIXIN
                    uni.reLaunch({
                        url: '/pages/login/login'
                    });
                    // #endif
                } else if (error.statusCode === 400) {
                    uni.reLaunch({
                        url: '/pages/stop/stop'
                    });
                } else {

                }
            },
            fail(e) {
            }
        });
    }

    app.config.globalProperties.$Uplode = async(uploadSuccess, i,count=1) => { //全局上传图片(uploadSuccess回调函数)
        const hasPermission = await checkAndRequestStoragePermission();
        if (!hasPermission) {
            return;
        }
        let token = ''
        try {
            token = uni.getStorageSync('userInfo').token
        } catch (e) {

        }
        uni.request({
            url: app.config.globalProperties.$baseurl + 'api/token/',
            method: 'GET',
            header: {
                'token': token
            },
            success: res => {
                if (app.config.globalProperties.$store.state.encryption) {
                    try {
                        res.data.data = JSON.parse(app.config.globalProperties.$decrypt(
                            res.data.data))
                    } catch (e) {
                        //TODO handle the exception
                    }

                }
                let upload = res.data.data
                setTimeout(() => {
                    // #ifndef MP-WEIXIN
                    uni.chooseImage({
                        count: count, //默认9
                        sizeType: ['original', 'compressed'],
                        sourceType: ['album', 'camera '],
                        success: (ress) => {
                            let type
                            // #ifdef APP-PLUS
                            type = ress.tempFilePaths[0].split('.')
                            type = type[type.length - 1]
                            // #endif
                            // #ifndef APP-PLUS
                            type = ress.tempFiles[0].name.split('.')
                            type = type[type.length - 1]
                            // #endif
                            console.log(ress)
                            ress.tempFilePaths.forEach((item, index) => {
                                uni.uploadFile({
                                    url: upload
                                        .upload, //仅为示例，非真实的接口地址
                                    filePath: item,
                                    name: 'file',
                                    header: {
                                        token: upload.token
                                    },
                                    formData: {
                                        key: app.config
                                                .globalProperties
                                                .$template + '/' +
                                            String(Math.round(
                                                new Date() /
                                                1000)) + String(
                                                parseInt(Math
                                                        .random() *
                                                    10000)) +
                                            '.' + type,
                                        token: upload.token
                                    },
                                    header: {
                                        token: upload.token
                                    },
                                    success: (
                                        uploadFileRes) => {
                                        let obj = {
                                            data: ress
                                        }
                                        uploadSuccess(upload
                                            .url + JSON
                                            .parse(
                                                uploadFileRes
                                                    .data)
                                            .key, obj, i
                                        )



                                    }
                                });

                            })
                        },
                        fail() {
                            // uni.showToast({
                            //     icon: 'none',
                            //     title: '123'
                            // })
                        }
                    });
                    // #endif
                    // #ifdef MP-WEIXIN
                    uni.chooseMedia({
                        mediaType: ['image'],
                        count: 9, //默认9
                        sizeType: ['original', 'compressed'],
                        sourceType: ['album', 'camera'],
                        camera: 'back',
                        success: (ress) => {
                            let type = ress.tempFiles[0]
                                .tempFilePath
                            type = type[type.length - 1]
                            uni.uploadFile({
                                url: upload
                                    .upload, //仅为示例，非真实的接口地址
                                filePath: ress.tempFiles[0]
                                    .tempFilePath,
                                name: 'file',
                                header: {
                                    token: upload.token
                                },
                                formData: {
                                    key: app.config
                                            .globalProperties
                                            .template + '/' +
                                        String(Math.round(
                                            new Date() /
                                            1000)) + String(
                                            parseInt(Math
                                                    .random() *
                                                10000)) +
                                        '.' + type,
                                    token: upload.token
                                },
                                header: {
                                    token: upload.token
                                },
                                success: (
                                    uploadFileRes) => {
                                    let obj = {
                                        data: ress
                                    }
                                    uni.hideLoading();
                                    uploadSuccess(upload
                                        .url + JSON
                                        .parse(
                                            uploadFileRes
                                                .data)
                                        .key, obj, i
                                    )
                                }
                            });
                        },
                        fail() {
                            console.log(fail)
                        }
                    });
                    // #endif
                }, 100)

            },
            fail(e) {
            }

        });
    }
    app.config.globalProperties.$UplodeVideo = (uploadSuccess,) => { //全局上传图片(uploadSuccess回调函数)
        let token = ''
        try {
            token = uni.getStorageSync('userInfo').token
        } catch (e) {
        }
        uni.request({
            url: app.config.globalProperties.$baseurl + 'api/token/',
            method: 'GET',
            header: {
                'token': token
            },
            success: res => {
                if (app.config.globalProperties.$store.state.encryption) {
                    try {
                        res.data.data = JSON.parse(app.config.globalProperties.$decrypt(
                            res.data.data))
                    } catch (e) {
                        //TODO handle the exception
                    }

                }
                console.log(res)
                let upload = res.data.data
                setTimeout(() => {
                    uni.chooseVideo({
                        sizeType: ['original', 'compressed'],
                        sourceType: ['album', 'camera '],
                        success: (ress) => {

													console.log(ress.tempFilePath)
													let type
													if(ress.tempFile) {
														type = ress.tempFile.name.split('.')
														type = type[type.length - 1]
													}else{
														type = ress.tempFilePath.split('.')
														type = type[type.length - 1]
													}

                            // let type
                            // // #ifdef APP-PLUS
                            // type = ress.tempFilePaths.split('.')
                            // // type = type[type.length - 1]
                            // // #endif
                            // // #ifndef APP-PLUS
                            // type = ress.tempFilePaths.name.split('.')
                            // // type = type[type.length - 1]
                            // // #endif
                            uni.uploadFile({
                                url: upload
                                    .upload, //仅为示例，非真实的接口地址
                                filePath: ress.tempFilePath,
                                name: 'file',
                                header: {
                                    token: upload.token
                                },
                                formData: {
                                    key: app.config
                                            .globalProperties
                                            .$template + '/' +
                                        String(Math.round(
                                            new Date() /
                                            1000)) + String(
                                            parseInt(Math
                                                    .random() *
                                                10000)) +
                                        '.' + type,
                                    token: upload.token
                                },
                                header: {
                                    token: upload.token
                                },
                                success: (
                                    uploadFileRes) => {
                                    uploadSuccess(upload
                                        .url + JSON
                                        .parse(
                                            uploadFileRes
                                                .data)
                                        .key)

																				console.log(JSON.parse(uploadFileRes.data),'12321')
                                }
                            });
                        },
                        fail(fail) {
                            console.log(fail)
                        }
                    });

                }, 100)
            },
            fail(e) {
            }

        });
    }
    app.config.globalProperties.$requestPromise = async (data) => {
        let token = '';
        let p = ''
        try {
            p = uni.getStorageSync('userInfo').p
        } catch (e) {

        }
        try {
            const userInfo = uni.getStorageSync('userInfo');
            if (userInfo && userInfo.token) {
                token = userInfo.token;
            }
        } catch (e) {
            //TODO handle the exception
            console.error('Error getting token from storage:', e);
        }
        console.error('token:', token);
        const response = await new Promise((resolve, reject) => {
            uni.request({
                url: app.config.globalProperties.$baseurl + data.url,
                method: data.method,
                data: data.method === 'GET' ? {} : JSON.stringify(data
                    .data), // 注意：GET 请求通常不使用 data 字段发送数据
                params: data.method === 'GET' ? data.data :
                    {}, // 注意：params 用于 GET 请求的查询参数
                header: {
                    'p': p,
                    'token': token,
                    'encryption': app.config.globalProperties.$store.state
                        .encryption
                },
                success: res => {
                    if (app.config.globalProperties.$store.state
                        .encryption) {
                        try {
                            res.data.data = JSON.parse(app.config
                                .globalProperties.$decrypt(res.data
                                    .data))
                        } catch (e) {
                            //TODO handle the exception
                        }
                    }
                    if (res.statusCode === 200) {
                        resolve(res.data);
                        reject(res);
                    } else if (error.statusCode ===
                        403) { // 处理错误情况，例如重新登录、显示错误信息等
                        uni.setStorageSync('userInfo', {});
                        // #ifdef MP-WEIXIN
                        uni.switchTab({
                            url: '/pages/personal/index'
                        });
                        // #endif
                        // #ifndef MP-WEIXIN
                        uni.reLaunch({
                            url: '/pages/login/login'
                        });
                        // #endif
                    } else if (error.statusCode === 400) {
                        uni.reLaunch({
                            url: '/pages/stop/stop'
                        });
                    } else {
                        // 处理其他错误情况
                        console.error('Request failed:', error);
                    }

                },
                fail: e => {
                    reject(e);
                }
            });
        });
        return response; // 返回响应数据，以便在 async 函数外部使用
    };
    app.config.globalProperties.$request = (data) => { //全局接口请求
        let token = ''
        let p = ''
        try {
            p = uni.getStorageSync('userInfo').p
        } catch (e) {

        }
        try {
            const userInfo = uni.getStorageSync('userInfo');
            if (userInfo && userInfo.token) {
                token = userInfo.token;
            }
        } catch (e) {
            //TODO handle the exception
            console.error('Error getting token from storage:', e);
        }
        uni.request({
            url: app.config.globalProperties.$baseurl + data.url,
            method: data.method,
            data: JSON.stringify(data.data),
            params: JSON.stringify(data
                .data), //data.method=='get'||data.method=='GET'?JSON.stringify(data.data):'',
            header: {
                'p': p,
                'token': token,
                'encryption': app.config.globalProperties.$store.state.encryption
            },
            success: res => {

                if (app.config.globalProperties.$store.state.encryption) {
                    try {
                        res.data.data = JSON.parse(app.config.globalProperties.$decrypt(
                            res.data.data))
                    } catch (e) {
                        //TODO handle the exception
                    }

                }
                if (res.statusCode == 200) {
                    // console.log("接口放回的参数：",res.data)
                    // uni.removeStorageSync('str')
                    data.success(res.data);
                } else if (res.statusCode == 403) {
                    const {fullPath}=getLoction()
                    uni.setStorageSync('str',fullPath)

                    uni.setStorageSync('userInfo', {});
                    // #ifdef MP-WEIXIN
                    uni.switchTab({
                        url: '/pages/personal/index'
                    });
                    // #endif
                    // #ifndef MP-WEIXIN
                    uni.reLaunch({
                        url: '/pages/login/login'
                    });
                    // #endif
                } else if (res.statusCode === 400) {
                    uni.reLaunch({
                        url: '/pages/stop/stop'
                    });
                } else if (res.statusCode === 429) {

                } else {

                }

            },
            fail(e) {
            }

        });
    }
    app.config.globalProperties.$SHOPrequest = (data) => { //全局接口请求
        let token = ''
        try {
            token = uni.getStorageSync('businessToken')
        } catch (e) {
            //TODO handle the exception
        }
        uni.request({
            url: app.config.globalProperties.$SHOPbaseurl + data.url,
            method: data.method,
            data: JSON.stringify(data.data),
            header: {
                'business': token,
                'encryption': app.config.globalProperties.$store.state.encryption
            },
            success: res => {
                if (app.config.globalProperties.$store.state.encryption) {
                    try {
                        res.data.data = JSON.parse(app.config.globalProperties.$decrypt(
                            res.data.data))
                    } catch (e) {
                        //TODO handle the exception
                    }

                }
                if (res.statusCode == 200) {
                    data.success(res.data);
                } else if (res.statusCode == 403) {
                    uni.switchTab({
                        url: '/pages/personal/index'
                    });
                } else {
                    // #ifndef  MP-WEIXIN
                    //  #endif
                }
            },
            fail(e) {

            }

        });
    }
    // 使用全局方法
    // app.use(globalMethods);
    // 引入vuex
    app.use(store)
    return {
        app
    }
}

